define(['jquery', 'bootstrap', 'perfect-scrollbar', 'aojie', 'editor', 'jquery-tagsinput'], function ($, undefined, PerfectScrollbar, Aojie) {
    var Backend = {
        api: {
            replaceids: function (elem, url) {
                //如果有需要替换ids的
                if (url.indexOf("{ids}") > -1) {
                    var ids = 0;
                    var tableId = $(elem).data("table-id");
                    if (tableId && $("#" + tableId).size() > 0 && $("#" + tableId).data("bootstrap.table")) {
                        var Table = require("table");
                        ids = Table.api.selectedids($("#" + tableId)).join(",");
                    }
                    url = url.replace(/\{ids\}/g, ids);
                }
                return url;
            },
            gettablecolumnbutton: function (options) {
                if (typeof options.tableId !== 'undefined' && typeof options.fieldIndex !== 'undefined' && typeof options.buttonIndex !== 'undefined') {
                    var tableOptions = $("#" + options.tableId).bootstrapTable('getOptions');
                    if (tableOptions) {
                        var columnObj = null;
                        $.each(tableOptions.columns, function (i, columns) {
                            $.each(columns, function (j, column) {
                                if (typeof column.fieldIndex !== 'undefined' && column.fieldIndex === options.fieldIndex) {
                                    columnObj = column;
                                    return false;
                                }
                            });
                            if (columnObj) {
                                return false;
                            }
                        });
                        if (columnObj) {
                            return columnObj['buttons'][options.buttonIndex];
                        }
                    }
                }
                return null;
            },
        },
        init: function () {
            //主题色变换时停止事件
            $("body").on('click', '[data-stopPropagation]', function (e) {
                e.stopPropagation();
            });
            // 滚动条
            if ($('.lyear-layout-sidebar-scroll').size() > 0) {
                new PerfectScrollbar('.lyear-layout-sidebar-scroll', {
                    swipeEasing: false,
                    suppressScrollX: true
                });
            }
            // 侧边栏
            $(".lyear-aside-toggler").bind('click', function () {
                $('.lyear-layout-sidebar').toggleClass('lyear-aside-open');
                $("body").toggleClass('lyear-layout-sidebar-close');
                $("#iframepage").toggleClass('lyear-layout-sidebar-close');

                if ($('.lyear-mask-modal').length == 0) {
                    $('<div class="lyear-mask-modal"></div>').prependTo('body');
                } else {
                    $('.lyear-mask-modal').remove();
                }
                $('.lyear-mask-modal').on('click', function () {
                    $(this).remove();
                    $('.lyear-layout-sidebar').toggleClass('lyear-aside-open');
                    $('body').toggleClass('lyear-layout-sidebar-close');
                });
            });
            // 侧边栏导航
            $('.nav-item-has-subnav > a').on('click', function () {
                $subnavToggle = jQuery(this);
                $navHasSubnav = $subnavToggle.parent();
                $topHasSubNav = $subnavToggle.parents('.nav-item-has-subnav').last();
                $subnav = $navHasSubnav.find('.nav-subnav').first();
                $viSubHeight = $navHasSubnav.siblings().find('.nav-subnav:visible').outerHeight();
                $scrollBox = $('.lyear-layout-sidebar-scroll');
                $navHasSubnav.siblings().find('.nav-subnav:visible').slideUp(500).parent().removeClass('open');
                $subnav.slideToggle(300, function () {
                    $navHasSubnav.toggleClass('open');

                    // 新增滚动条处理
                    var scrollHeight = 0;
                    pervTotal = $topHasSubNav.prevAll().length,
                        boxHeight = $scrollBox.outerHeight(),
                        innerHeight = $('.sidebar-main').outerHeight(),
                        thisScroll = $scrollBox.scrollTop(),
                        thisSubHeight = $(this).outerHeight(),
                        footHeight = 121;

                    if (footHeight + innerHeight - boxHeight >= (pervTotal * 48)) {
                        scrollHeight = pervTotal * 48;
                    }
                    if ($subnavToggle.parents('.nav-item-has-subnav').length == 1) {
                        $scrollBox.animate({scrollTop: scrollHeight}, 300);
                    } else {
                        // 子菜单操作
                        if (typeof ($viSubHeight) != 'undefined' && $viSubHeight != null) {
                            scrollHeight = thisScroll + thisSubHeight - $viSubHeight;
                            $scrollBox.animate({scrollTop: scrollHeight}, 300);
                        } else {
                            if ((thisScroll + boxHeight - $scrollBox[0].scrollHeight) == 0) {
                                scrollHeight = thisScroll - thisSubHeight;
                                $scrollBox.animate({scrollTop: scrollHeight}, 300);
                            }
                        }
                    }
                });
            });
            //根据当前导航url设置active
            var current_url = window.location.pathname;
            var tag = 'a[url="' + current_url + '"]';
            $('.nav-item').removeClass('active');
            var parents = $(tag).parents('.nav-item');
            if (parents.hasClass('nav-item-has-subnav')) {
                parents.addClass('open');
            }
            parents.addClass('active');
            //用户按钮
            $(document).on('click', '.btn-user-click', function () {
                var type = $(this).data('type');
                var url = $(this).data('url');
                var text = $(this).text();
                var value = $(this).data('value');
                if (type == 'dialog') {
                    Aojie.api.open(url, text);
                } else {
                    var obj = {
                        method: 'post',
                        url: url,
                        data: {
                            type: value
                        }
                    }
                    Aojie.api.axios(obj);
                }
            })
            //
            //添加ios-fix兼容iOS下的iframe
            if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
                $("html").addClass("ios-fix");
            }
            //配置Toastr的参数
            Toastr.options.positionClass = Config.controller_name.toLowerCase() === 'index' ? "toast-top-center" : "toast-top-right";
            //点击包含.btn-dialog的元素时弹出dialog
            $(document).on('click', '.btn-dialog,.dialogit', function (e) {
                var that = this;
                var options = $.extend({}, $(that).data() || {});
                var url = Backend.api.replaceids(that, $(that).data("url") || $(that).attr('href'));
                var title = $(that).attr("title") || $(that).data("title") || $(that).data('original-title');
                var button = Backend.api.gettablecolumnbutton(options);
                if (button && typeof button.callback === 'function') {
                    options.callback = button.callback;
                }
                if (typeof options.confirm !== 'undefined') {
                    layer.confirm(options.confirm, function (index) {
                        Backend.api.open(url, title, options);
                        layer.close(index);
                    });
                } else {
                    window[$(that).data("window") || 'self'].Backend.api.open(url, title, options);
                }
                return false;
            });
            //点击包含.btn-addtabs的元素时新增选项卡
            $(document).on('click', '.btn-addtabs,.addtabsit', function (e) {
                var that = this;
                var options = $.extend({}, $(that).data() || {});
                var url = Backend.api.replaceids(that, $(that).data("url") || $(that).attr('href'));
                var title = $(that).attr("title") || $(that).data("title") || $(that).data('original-title');
                var icon = $(that).attr("icon") || $(that).data("icon");
                if (typeof options.confirm !== 'undefined') {
                    layer.confirm(options.confirm, function (index) {
                        Backend.api.addtabs(url, title, icon);
                        layer.close(index);
                    });
                } else {
                    Backend.api.addtabs(url, title, icon);
                }
                return false;
            });
            //点击包含.btn-ajax的元素时发送Ajax请求
            $(document).on('click', '.btn-ajax,.ajaxit', function (e) {
                var that = this;
                var options = $.extend({}, $(that).data() || {});
                if (typeof options.url === 'undefined' && $(that).attr("href")) {
                    options.url = $(that).attr("href");
                }
                options.url = Backend.api.replaceids(this, options.url);
                var success = typeof options.success === 'function' ? options.success : null;
                var error = typeof options.error === 'function' ? options.error : null;
                delete options.success;
                delete options.error;
                var button = Backend.api.gettablecolumnbutton(options);
                if (button) {
                    if (typeof button.success === 'function') {
                        success = button.success;
                    }
                    if (typeof button.error === 'function') {
                        error = button.error;
                    }
                }
                //如果未设备成功的回调,设定了自动刷新的情况下自动进行刷新
                if (!success && typeof options.tableId !== 'undefined' && typeof options.refresh !== 'undefined' && options.refresh) {
                    success = function () {
                        $("#" + options.tableId).bootstrapTable('refresh');
                    }
                }
                if (typeof options.confirm !== 'undefined') {
                    layer.confirm(options.confirm, function (index) {
                        Backend.api.axios(options, success, error);
                        layer.close(index);
                    });
                } else {
                    Backend.api.axios(options, success, error);
                }
                return false;
            });

            $(document).on('click', '.btn-click,.clickit', function (e) {
                var that = this;
                var options = $.extend({}, $(that).data() || {});
                var row = {};
                if (typeof options.tableId !== 'undefined') {
                    var index = parseInt(options.rowIndex);
                    var data = $("#" + options.tableId).bootstrapTable('getData');
                    row = typeof data[index] !== 'undefined' ? data[index] : {};
                }
                var button = Backend.api.gettablecolumnbutton(options);
                var click = typeof button.click === 'function' ? button.click : $.noop;

                if (typeof options.confirm !== 'undefined') {
                    layer.confirm(options.confirm, function (index) {
                        click.apply(that, [options, row, button]);
                        layer.close(index);
                    });
                } else {
                    click.apply(that, [options, row, button]);
                }
                return false;
            });
            //修复含有fixed-footer类的body边距
            if ($(".fixed-footer").size() > 0) {
                $(document.body).css("padding-bottom", $(".fixed-footer").outerHeight());
            }

            //开关选项
            $(document).on('change', '.lyear-switch>input', function (e) {
                var that = $(this);
                var yes = that.data('yes');
                var no = that.data('no');
                if (that.is(':checked')) {
                    var value = yes ? yes : 1;
                    that.parent('.lyear-switch').find('input[type="hidden"]').remove();
                    that.val(value);
                } else {
                    var value = no ? no : 0;
                    that.val(value);
                    var name = that.attr('name');
                    var htmls = '<input type="hidden" name="'+name+'" value="'+value+'">';
                    that.parent('.lyear-switch').append(htmls);
                }
            });
            $(".lyear-switch>input").trigger('change');
            // // 提示
            // if ($('[data-toggle="tooltip"]')[0]) {
            //     $('[data-toggle="tooltip"]').tooltip({
            //         "container": 'body',
            //     });
            // }
            //
            // // 弹出框
            // if ($('[data-toggle="popover"]')[0]) {
            //     $('[data-toggle="popover"]').popover();
            // }

            // 标签
            // if ($('.js-tags-input')[0]) {
            //     $('.js-tags-input').tagsInput({
            //         height: '36px',
            //         width: '100%',
            //         defaultText:'添加标签',
            //         removeWithBackspace: true,
            //         delimiter: [',']
            //     });
            // }

            // 时间选择
            // jQuery('.js-datetimepicker').each(function () {
            //     var $input = jQuery(this);
            //     $input.datetimepicker({
            //         format: $input.data('format') ? $input.data('format') : false,
            //         useCurrent: $input.data('use-current') ? $input.data('use-current') : false,
            //         locale: moment.locale('' + ($input.data('locale') ? $input.data('locale') : '') + ''),
            //         showTodayButton: $input.data('show-today-button') ? $input.data('show-today-button') : false,
            //         showClear: $input.data('show-clear') ? $input.data('show-clear') : false,
            //         showClose: $input.data('show-close') ? $input.data('show-close') : false,
            //         sideBySide: $input.data('side-by-side') ? $input.data('side-by-side') : false,
            //         inline: $input.data('inline') ? $input.data('inline') : false,
            //     });
            // });

            // 日期选择
            // jQuery('.js-datepicker').each(function () {
            //     var $input = jQuery(this);
            //     $input.datepicker({
            //         weekStart: 1,
            //         autoclose: true,
            //         todayHighlight: true,
            //         language: 'zh-CN',
            //     });
            // });

            // 颜色选取
            // jQuery('.js-colorpicker').each(function () {
            //     var $colorpicker = jQuery(this);
            //     var $colorpickerMode = $colorpicker.data('colorpicker-mode') ? $colorpicker.data('colorpicker-mode') : 'hex';
            //     var $colorpickerinline = $colorpicker.data('colorpicker-inline') ? true : false;
            //     $colorpicker.colorpicker({
            //         'format': $colorpickerMode,
            //         'inline': $colorpickerinline
            //     });
            // });

            // 复选框全选
            $("#check-all").change(function () {
                $("input[type='checkbox']").prop('checked', $(this).prop("checked"));
            });

            // 设置主题配色
            setTheme = function (input_name, data_name) {
                $("input[name='" + input_name + "']").click(function () {
                    $('body').attr(data_name, $(this).val());
                });
            }
            setTheme('site_theme', 'data-theme');
            setTheme('logo_bg', 'data-logobg');
            setTheme('header_bg', 'data-headerbg');
            setTheme('sidebar_bg', 'data-sidebarbg');
        },
        events: {},


    };
    Backend.api = $.extend(Aojie.api, Backend.api);
    //将Backend渲染至全局,以便于在子框架中调用
    window.Backend = Backend;
    Backend.init();
    return Backend;

});
